//
//  LBPhotoBrowser
//  app
//
//  Created by LINAICAI on 16/8/10.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBPhotoBrowser.h"
#import "LBPhotoCell.h"
#import "LBPhotoTransition.h"
#import <Masonry/Masonry.h>
static NSString *const cellID = @"LBPhotoCell";
@interface LBPhotoBrowser ()<UIViewControllerTransitioningDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
///数据源
@property (nonatomic , strong)NSArray<LBPhoto*> *dataSources;
///主页面
@property (nonatomic , strong)UICollectionView *collectionView;
///布局
@property (nonatomic , strong)UICollectionViewFlowLayout *layout;
///页码标签
@property (nonatomic , strong)UILabel *pageLabel;
///当前页码
@property (nonatomic , assign)NSInteger currentIndex;

@property (nonatomic , assign)BOOL isOriginalStatusBarHidden;


@property (nonatomic , strong)LBPhotoTransition<UIViewControllerAnimatedTransitioning> *presentPhotoTransition;
@property (nonatomic , strong)LBPhotoTransition<UIViewControllerAnimatedTransitioning> *dismissPhotoTransition;
@end

@implementation LBPhotoBrowser
- (UIImageView *)sourceImageView{
    if (self.sourceImageViewClosure) {
        return self.sourceImageViewClosure(self.currentIndex);
    }
    return nil;
}
- (UIImageView *)displayImageView{
    LBPhotoCell *cell = (LBPhotoCell *)self.collectionView.visibleCells.lastObject;
    return cell.imageView;
}
- (LBPhotoTransition<UIViewControllerAnimatedTransitioning> *)presentPhotoTransition{
    if (!_presentPhotoTransition) {
        _presentPhotoTransition = [[LBPhotoTransition<UIViewControllerAnimatedTransitioning> alloc]initWithType:LBPhotoTransitionPresent];
    }
    return _presentPhotoTransition;
}
- (LBPhotoTransition<UIViewControllerAnimatedTransitioning> *)dismissPhotoTransition{
    if (!_dismissPhotoTransition) {
        _dismissPhotoTransition = [[LBPhotoTransition<UIViewControllerAnimatedTransitioning> alloc]initWithType:LBPhotoTransitionDismiss];
    }
    return _dismissPhotoTransition;
}
- (UILabel *)pageLabel{
    if (!_pageLabel) {
        _pageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height-40, self.view.bounds.size.width, 20)];
        _pageLabel.font = [UIFont boldSystemFontOfSize:16];
        _pageLabel.textColor = [UIColor whiteColor];
        _pageLabel.textAlignment = NSTextAlignmentCenter;
        _pageLabel.text = [NSString stringWithFormat:@"%ld/%lu",self.currentIndex+1,(unsigned long)self.dataSources.count];
    }
    return _pageLabel;
}
- (UICollectionViewFlowLayout *)layout{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc]init];
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _layout.itemSize = self.view.bounds.size;
        _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, _layout.minimumLineSpacing);
    }
    return _layout;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.layout.itemSize.width + self.layout.minimumLineSpacing, self.layout.itemSize.height) collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [_collectionView registerClass:[LBPhotoCell class] forCellWithReuseIdentifier:cellID];
    }
    return _collectionView;
}
#pragma mark - life cycle
/**
 *  初始化构造方法
 *
 *  @param photos 图片URL数组
 *
 *  @return 对象实例
 */
- (instancetype)initWithPhotos:(NSArray<LBPhoto *> *)photos selectIndex:(NSUInteger)selectIndex sourceImageViewClosure:(SourceImageViewClosure)sourceImageViewClosure{
    self = [super init];
    if (self) {
        self.currentIndex = selectIndex;
        self.dataSources = photos;
        self.sourceImageViewClosure = sourceImageViewClosure;
    }
    return self;
}
/**
 *  工厂方法
 *
 *  @param photos 图片URL数组
 */

+ (void)showWithPhotos:(NSArray<LBPhoto *> *)photos selectIndex:(NSUInteger)selectIndex sourceImageViewClosure:(SourceImageViewClosure)sourceImageViewClosure{
    LBPhotoBrowser *vc = [[LBPhotoBrowser alloc]initWithPhotos:photos selectIndex:selectIndex sourceImageViewClosure:sourceImageViewClosure];
    [vc setTransitioningDelegate:vc];
    vc.modalPresentationStyle = UIModalPresentationCustom;
    [vc setModalPresentationCapturesStatusBarAppearance:YES];
    UIViewController *controller = [UIApplication sharedApplication].delegate.window.rootViewController;
    [controller presentViewController:vc animated:YES completion:nil];
}
#pragma mark - view cycle
- (void)dealloc{
    self.delegate = nil;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.collectionView.hidden = NO;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.collectionView.hidden = self.sourceImageView != nil;
    //记录状态栏的状态，以便dismiss的时候恢复到原来的样子
    self.isOriginalStatusBarHidden = [UIApplication sharedApplication].isStatusBarHidden;
    

}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden{
    return YES;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [self setupUI];
    [self setupGesture];
}
#pragma mark - private
- (LBPhoto *)currentPhoto{
    if (self.dataSources.count) {
        return self.dataSources[self.currentIndex];
    }
    return nil;
}
- (void)scrolToCurrentIndex:(BOOL)animated{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:animated];
}
- (void)setupUI{
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.pageLabel];
    [self scrolToCurrentIndex:NO];
}
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
}
- (void)setupGesture{
    ///双击手势
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap)];
    doubleTap.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:doubleTap];
    ///单击手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap)];
    [self.view addGestureRecognizer:singleTap];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    ///长按手势
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
//    [self.view addGestureRecognizer:longPress];
    
    ///拖动收拾
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
//    [self.view addGestureRecognizer:pan];

    

}
#pragma mark - Event
- (void)pan:(UIPanGestureRecognizer *)pan{
    CGPoint transition = [pan translationInView:self.view];
    LBPhotoCell *cell = self.collectionView.visibleCells.lastObject;
    
    switch (pan.state) {
    case UIGestureRecognizerStateBegan:
            break;
    case UIGestureRecognizerStateEnded:
    case UIGestureRecognizerStateCancelled:
    case UIGestureRecognizerStateFailed:
    case UIGestureRecognizerStatePossible:
        {
            //拖动图片往下拖动超过100像素就退出大图浏览模式
            //该参数有待调整
            if (transition.y > 100 ){
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else {
                [UIView animateWithDuration:0.25 animations:^{
                    cell.transform = CGAffineTransformIdentity;
                }];
            }

        }
            break;
            
    case UIGestureRecognizerStateChanged:
        {
            CGFloat scale = 1 - transition.y / [UIScreen mainScreen].bounds.size.height;
            CGAffineTransform transform = CGAffineTransformMakeTranslation(transition.x, transition.y);
            if (transition.y > 0) {
                //往下拖动图片的时候做缩放
                transform =CGAffineTransformConcat(transform,CGAffineTransformMakeScale(scale, scale))  ;
            }
            cell.transform = transform;
        }
            break;
            default:
                break;

        
        
    }
    
    
}

- (void)doubleTap{
    LBPhotoCell *cell =(LBPhotoCell*)self.collectionView.visibleCells.lastObject;
    if (cell) {
        [cell didZoom];
    }
}

- (void)singleTap{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)longPress:(UILongPressGestureRecognizer *)longPress{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        ///弹出操作表
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSources.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LBPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    if (!cell) {
        cell = [[LBPhotoCell alloc]init];
    }
    cell.photo = self.dataSources[indexPath.item];
    return cell;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //计算新页码
    self.currentIndex = ((scrollView.contentOffset.x / scrollView.bounds.size.width) + 0.5);
    //设置页码标签
    self.pageLabel.text = [NSString stringWithFormat:@"%ld/%lu",self.currentIndex+1,(unsigned long)self.dataSources.count];
}
#pragma mark - UIViewControllerTransitioningDelegate
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return self.presentPhotoTransition;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return self.dismissPhotoTransition;
}


@end
